package com.broada.apm.thrift.impl;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.Constants;
import com.broada.apm.thrift.ThriftTransportValidate;
import com.broada.apm.thrift.model.TSocketExt;
import com.broada.apm.thrift.model.ThriftServiceName;
import com.broada.apm.thrift.service.ThriftTransportValidateController;

/**
 * 默认实现
 * @author jianfei.xu
 * @date   2016年3月25日
 *
 */
public class DefaultThriftTransportValidate implements ThriftTransportValidate {
	@Override
	public boolean isValidate(TTransport transport) {
		if(null != transport) ((TSocket)transport).setSocketTimeout(Constants.thriftValidateReadTimeout);
		TProtocol protocol = new TBinaryProtocol(transport);
		TMultiplexedProtocol mProtocol = new TMultiplexedProtocol(protocol, ThriftServiceName.THRIFT_SERVICE_VALIDATE);
		boolean isBad = true;
		try {
			ThriftTransportValidateController.Client client = new ThriftTransportValidateController.Client(mProtocol);
			client.isOk();
			isBad = false;
		} catch (Exception e) {
			LOG.error("连接出现异常(错误类型:" + ((TTransportException)e).getType() + ")", e);
			if(e.getCause() instanceof java.net.SocketTimeoutException) {
				if(null != transport) ((TSocketExt)transport).setSocketTimeOut(true);
				return true;
			}
			
			return false;
		} finally {
			try {
				if(isBad && transport.isOpen()) {
					transport.close();
				}
			} catch (Exception e2) {
				LOG.error("尝试关闭TTransport失败!");
			}
		}
		
		if(null != transport) ((TSocket)transport).setSocketTimeout(Constants.thriftReadTimeout);
		
		return true;
	}

	private static Logger LOG = LoggerFactory.getLogger(DefaultThriftTransportValidate.class);
	
}
